package com.kvest.NewLocationTest;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.*;
import com.kvest.NewLocationTest.service.LocationService;

import java.util.Arrays;
import java.util.Collections;

public class NewLocationTestActivity extends Activity implements LocationClient.OnAddGeofencesResultListener{
    private ActivityRecognitionClient activityRecognitionClient;
    private PendingIntent activityRecognitionPendingIntent;
    private GooglePlayServicesClient.ConnectionCallbacks startActivityRecognitionCallbacks;
    private GooglePlayServicesClient.ConnectionCallbacks stopActivityRecognitionCallbacks;

    private LocationClient locationClient;
    private PendingIntent locationPendingIntent;
    private GooglePlayServicesClient.ConnectionCallbacks startConnectionCallbacks;
    private GooglePlayServicesClient.ConnectionCallbacks stopConnectionCallbacks;
    private GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListene;

    private TextView logTextView;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        logTextView = (TextView) findViewById(R.id.log_tv);

        createData();
    }

    private void createData() {
        if (locationPendingIntent == null) {
            Intent intent = new Intent(this, LocationService.class);
            intent.setAction(LocationService.ACTION_LOCATION);
            locationPendingIntent = PendingIntent.getService(this, 1, intent, 0);
        }

        if (activityRecognitionPendingIntent == null) {
            Intent intent = new Intent(this, LocationService.class);
            intent.setAction(LocationService.ACTION_ACTION);
            activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }

        if (startConnectionCallbacks == null) {
            startConnectionCallbacks = new GooglePlayServicesClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle bundle) {
                    if (locationClient != null && locationClient.isConnected()) {
                        LoggerService.getInstance().writeLog("start onConnected");

                        LocationRequest locationRequest = LocationRequest.create();
                        locationRequest.setInterval(15000);
                        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

                        locationClient.requestLocationUpdates(locationRequest, locationPendingIntent);

                        Location lastLocation = locationClient.getLastLocation();
                        LoggerService.getInstance().writeLog("LastLocation=" + (lastLocation != null ? lastLocation.toString() : "null"));
                        LoggerService.getInstance().writeLog("getInterval=" + locationRequest.getInterval());
                        LoggerService.getInstance().writeLog("getFastestInterval=" + locationRequest.getFastestInterval());

                        addGeofences();

                        locationClient.disconnect();
                        locationClient = null;
                    }
                }

                @Override
                public void onDisconnected() {
                    LoggerService.getInstance().writeLog("start onDisconnected");
                }
            };
        }

        if (stopConnectionCallbacks == null) {
            stopConnectionCallbacks = new GooglePlayServicesClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle bundle) {
                    if (locationClient != null && locationClient.isConnected()) {
                        LoggerService.getInstance().writeLog("stop onConnected");
                        locationClient.removeLocationUpdates(locationPendingIntent);

                        locationClient.disconnect();
                        locationClient = null;
                    }
                }

                @Override
                public void onDisconnected() {
                    LoggerService.getInstance().writeLog("stop onDisconnected");
                }
            };
        }

        if (connectionFailedListene == null) {
            connectionFailedListene = new GooglePlayServicesClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult connectionResult) {
                    LoggerService.getInstance().writeLog("onConnectionFailed " + connectionResult.toString());
                }
            };
        }

        if (startActivityRecognitionCallbacks == null) {
            startActivityRecognitionCallbacks = new GooglePlayServicesClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle bundle) {
                    if (activityRecognitionClient != null && activityRecognitionClient.isConnected()) {
                        activityRecognitionClient.requestActivityUpdates(30000, activityRecognitionPendingIntent);
                    }
                }

                @Override
                public void onDisconnected() {
                    LoggerService.getInstance().writeLog("start onDisconnected ActivityRecognition");
                }
            };
        }

        if (stopActivityRecognitionCallbacks == null) {
            stopActivityRecognitionCallbacks = new GooglePlayServicesClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle bundle) {
                    if (activityRecognitionClient != null && activityRecognitionClient.isConnected()) {
                        activityRecognitionClient.removeActivityUpdates(activityRecognitionPendingIntent);
                    }
                }

                @Override
                public void onDisconnected() {
                    LoggerService.getInstance().writeLog("stop onDisconnected ActivityRecognition");
                }
            };
        }
    }

    private void addGeofences() {
        //geofences
        Geofence geofence = new Geofence.Builder().setRequestId("softtechnics").setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                                    .setCircularRegion(46.463102, 30.711656, 150).setExpirationDuration(Geofence.NEVER_EXPIRE).build();
        Geofence geofence1 = new Geofence.Builder().setRequestId("first_cross").setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                                    .setCircularRegion(46.456960, 30.682167, 200).setExpirationDuration(Geofence.NEVER_EXPIRE).build();
        Geofence geofence2 = new Geofence.Builder().setRequestId("second_cross").setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                                    .setCircularRegion(46.442144,30.704549, 200).setExpirationDuration(Geofence.NEVER_EXPIRE).build();
        Geofence geofence3 = new Geofence.Builder().setRequestId("home").setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                                    .setCircularRegion(46.437720,30.722487, 150).setExpirationDuration(Geofence.NEVER_EXPIRE).build();
        Intent intent = new Intent(this, LocationService.class);
        intent.setAction(LocationService.ACTION_GEOFENCE);
        PendingIntent pi = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        locationClient.addGeofences(Arrays.asList(geofence, geofence1, geofence2, geofence3), pi, this);
    }

    @Override
    public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
        switch (statusCode) {
            case LocationStatusCodes.SUCCESS : LoggerService.getInstance().writeLog("onAddGeofencesResult=SUCCESS"); break;
            case LocationStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES : LoggerService.getInstance().writeLog("onAddGeofencesResult=GEOFENCE_TOO_MANY_GEOFENCES"); break;
            case LocationStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS : LoggerService.getInstance().writeLog("onAddGeofencesResult=GEOFENCE_TOO_MANY_PENDING_INTENTS"); break;
            case LocationStatusCodes.GEOFENCE_NOT_AVAILABLE : LoggerService.getInstance().writeLog("onAddGeofencesResult=GEOFENCE_NOT_AVAILABLE"); break;
            case LocationStatusCodes.ERROR : LoggerService.getInstance().writeLog("onAddGeofencesResult=ERROR"); break;
        }

        LoggerService.getInstance().writeLog("geofenceRequestIds=" + Arrays.toString(geofenceRequestIds));
    }

    public void onStartClick(View view) {
        locationClient = new LocationClient(this, startConnectionCallbacks, connectionFailedListene);
        locationClient.connect();

        activityRecognitionClient = new ActivityRecognitionClient(this, startActivityRecognitionCallbacks, connectionFailedListene);
        activityRecognitionClient.connect();
    }

    public void onStopClick(View view) {
        locationClient = new LocationClient(this, stopConnectionCallbacks, connectionFailedListene);
        locationClient.connect();

        activityRecognitionClient = new ActivityRecognitionClient(this,stopActivityRecognitionCallbacks , connectionFailedListene);
        activityRecognitionClient.connect();
    }
}
